package edu.sandau.b230111.b23011125.Controller;

import edu.sandau.b230111.b23011125.Global.GlobalDefine;
import edu.sandau.b230111.b23011125.Global.ProblemListWithProblems;
import edu.sandau.b230111.b23011125.Model.ProblemList;
import edu.sandau.b230111.b23011125.Service.ProblemListService;
import edu.sandau.b230111.b23011125.Service.ProblemService;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class ProblemListController {
    @Autowired
    private ProblemListService problemListService;
    @Autowired
    private ProblemService problemService;

    @RequestMapping("/problemlist/list")
    public String listAllProblemList(ModelMap map,HttpServletRequest request,@RequestParam(value = "page",defaultValue = "0") String pageCnt){
        String loggedUserid = (String)request.getSession().getAttribute("userid");
        if(null==loggedUserid){//未登录
            return "redirect:/login";
        }
        Integer pageIndex = Integer.parseInt(pageCnt);
        Page<ProblemList> problemlists = problemListService.queryAllProblemList(pageIndex, GlobalDefine.PAGESIZE);
        map.put("totalElement",problemlists.getTotalElements());
        map.put("totalPage",problemlists.getTotalPages());
        map.put("nowPage",problemlists.getNumber());
        List<ProblemList> problemlistscontent = problemlists.getContent();
        map.put("problemlists",problemlistscontent);
        String isAdmin = (String)request.getSession().getAttribute("isAdmin");
        if(isAdmin==null){
            map.put("isAdmin","NO");
        }
        else{
            map.put("isAdmin","YES");
        }
        return "problemlist_list";
    }

    @RequestMapping("/problemlist/{listid}")
    public String problemListDetails(ModelMap map,HttpServletRequest request,@PathVariable(name = "listid") String listid){
        String loggedUserid = (String)request.getSession().getAttribute("userid");
        if(null==loggedUserid){//未登录
            return "redirect:/login";
        }

        ProblemListWithProblems problemListWithProblems = problemListService.queryProblemListWithProblems(listid);
        if(problemListWithProblems==null){ //题单不存在
            return "notfound";
        }

        map.put("problemlist",problemListWithProblems);
        String isAdmin = (String)request.getSession().getAttribute("isAdmin");
        if(isAdmin==null){
            map.put("isAdmin","NO");
        }
        else{
            map.put("isAdmin","YES");
        }
        return "problemlist";
    }

}
